<?php

class address_slot_dao extends dao
{
    protected $table_name = 'address_slot';
    protected $db_config_key = 'default';

    public function query_count_by_address_units_group_by_address_unit_id($address_units)
    {/*{{{*/
        $address_unit_ids = [];

        foreach ($address_units as $address_unit) {

            otherwise($address_unit instanceof address_unit, __FUNCTION__.'的数组参数中传入了'.get_class($address_unit).'类型数据');

            $address_unit_ids[] = $address_unit->id;
        }

        $infos = db_query('
            select adut.address_unit_id, count(1) cnt
            from address_slot ads
            inner join address_unit_turn adut on adut.address_slot_id = ads.id and adut.delete_time is null
            where ads.delete_time is null
            and adut.address_unit_id in :address_unit_ids
            group by adut.address_unit_id
            ', [
                ':address_unit_ids' => $address_unit_ids,
            ], $this->db_config_key);

        return array_build($infos, function ($k, $v) {

            return [
                $v['address_unit_id'],
                $v['cnt'],
            ];
        });
    }/*}}}*/

    public function query_count_by_address_unit(address_unit $address_unit)
    {/*{{{*/
        return db_query_value('cnt', '
            select count(1) cnt
            from address_slot ads
            inner join address_unit_turn adut on adut.address_slot_id = ads.id and adut.delete_time is null
            where ads.delete_time is null
            and adut.address_unit_id = :address_unit_id
            ', [
                ':address_unit_id' => $address_unit->id,
            ], $this->db_config_key);
    }/*}}}*/

    public function find_all_by_estate_order_by_number(estate $estate)
    {/*{{{*/
        return $this->find_all_by_condition('estate_id = :estate_id and delete_time is null order by number asc', [
            ':estate_id' => $estate->id,
        ]);
    }/*}}}*/
}
